package com.xxx.demo.data.rest;

import com.github.butid.data.base.BaseCommand;
import com.github.butid.data.codec.ResultBody;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.config.CronTask;
import org.springframework.scheduling.config.ScheduledTask;
import org.springframework.scheduling.config.ScheduledTaskHolder;
import org.springframework.scheduling.config.Task;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author wangjing.dc@qq.com
 * @since 2020/9/15
 */
@Slf4j
@RestController
@RequestMapping("/springjob")
public class JobController extends BaseCommand {


    private final Collection<ScheduledTaskHolder> scheduledTaskHolders;

    public JobController(Collection<ScheduledTaskHolder> scheduledTaskHolders) {
        this.scheduledTaskHolders = scheduledTaskHolders;
    }

    @ApiOperation("手动执行定时任务")
    @GetMapping("/run")
    public ResultBody runTask(String taskName){
        List<Task> tasks = this.scheduledTaskHolders
                .stream().flatMap((holder) -> holder.getScheduledTasks().stream())
                .map(ScheduledTask::getTask)
                .filter(task -> {
                    return taskName.equals(task.toString());
                }).collect(Collectors.toList());

        if(tasks.size() <= 0) return this.error("定时任务不存在");

        new Thread(tasks.get(0).getRunnable(),"userScheduling").start();
        return this.success("");
    }

    @GetMapping("/list")
    public  List<SpringTask> list(){
        return this.scheduledTaskHolders
                .stream().flatMap((holder) -> holder.getScheduledTasks().stream())
                .map(ScheduledTask::getTask)
                .map(task -> {
                    if(task instanceof CronTask){
                        CronTask cronTask = (CronTask) task;
                        return new SpringTask(cronTask.toString(), cronTask.getExpression());
                    }else{
                        return null;
                    }
                })
                .filter(Objects::nonNull)
                .collect(Collectors.toList());
    }


    @Data
    @AllArgsConstructor
    public static class SpringTask{
        String cron;
        String name;
    }

}
